package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.tabrepay

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.tabrepay.showMessage
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityGhanaTabRepayBinding
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.hitPoint
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.me.MeGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.permissions.PermissionGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.repay.RepayGhanaActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.subview.HotlineGhanaDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.tabrepay.subview.ITabRepayGhanaSliderListener
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.analytics.util.AnalyticsUtil
import org.json.JSONObject

class TabRepayGhanaActivity : AppCompatActivity() {

    private lateinit var tabRepayViewModel: TabRepayGhanaViewModel
    private lateinit var binding: ActivityGhanaTabRepayBinding
    private lateinit var adapter: TabRepayGhanaPageAdapter

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n", "ResourceType")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        tabRepayViewModel = ViewModelProvider(this)[TabRepayGhanaViewModel::class.java]

        // 关联布局
        binding = ActivityGhanaTabRepayBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val back = binding.navbarLeft
        val hotline = binding.navbarRight
        val loading = binding.loading
        val totalAmount = binding.totalAmount
        val availableAmount = binding.availableAmount
        val availablePercent = binding.availablePercent
        val usedAmount = binding.usedAmount
        val minAmount = binding.minAmount
        val maxAmount = binding.maxAmount
        val expireDate = binding.expireDate
        val flexiblePayTips = binding.flexiblePayTips
        val remindProcess = binding.remindProcess
        val sliderAmount = binding.sliderAmount
        val slider = binding.slider
        val list = binding.list
        val submit = binding.submit
        val tabMe = binding.tabMe
        val refresh = binding.refresh

        // 初始化下拉刷新
        refresh.apply {
            setColorSchemeColors(Color.parseColor("#5277D6"))

            setOnRefreshListener { tabRepayViewModel.pageDetail() }
        }

        // 初始化adapter
        adapter = TabRepayGhanaPageAdapter(emptyList(), object : ITabRepayGhanaPlanAdapter {
            override fun onClickPlan(orderId: String) {
                hitPoint("TAB_REPAY_PLAN_CLICK", orderId)

                val intent = Intent(this@TabRepayGhanaActivity, RepayGhanaActivity::class.java)
                intent.putExtra("orderId", orderId)
                startActivity(intent)
            }
        })
        list.layoutManager = LinearLayoutManager(this)
        list.adapter = adapter
        list.isNestedScrollingEnabled = false

        // 页面loading状态接口监听
        tabRepayViewModel.loadingResult.observe(this@TabRepayGhanaActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                refresh.isRefreshing = false
                loading.visibility = View.GONE
            }
        })

        // 页面详情接口监听
        tabRepayViewModel.pageDetailResult.observe(this@TabRepayGhanaActivity, Observer {
            val pageDetailResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (pageDetailResult.error != null) {
                showMessage(pageDetailResult.error)
            }
            if (pageDetailResult.success != null) {
                totalAmount.text = pageDetailResult.success.optString("maxAmount")
                expireDate.text = pageDetailResult.success.optString("dueDate")
                usedAmount.text = pageDetailResult.success.optString("utilisedAmount")
                minAmount.text = pageDetailResult.success.optString("minAmount")
                maxAmount.text = pageDetailResult.success.optString("availableAmount")
                availableAmount.text = pageDetailResult.success.optString("availableAmount")
                flexiblePayTips.text = pageDetailResult.success.optString("flexiblePayTips")
                availablePercent.text = pageDetailResult.success.optString("availablePercent")

                val sliderAmountStr = pageDetailResult.success.optString("sliderAmount", "0")
                sliderAmount.text = sliderAmountStr

                // 更新可借进度条
                val process = pageDetailResult.success.optString("availableProcess")
                remindProcess.updateProcess(process.toFloat())

                // 默认
                slider.reset()

                // 更新slider配置
                val minInt = minAmount.text.toString().toInt()
                val maxInt = maxAmount.text.toString().toInt()
                slider.setStepConfig(min = minInt, max = maxInt, step = 100)
                if (maxInt == minInt) {
                    slider.setProcess(1F)
                }
            }
        })

        // 页面展示行接口监听
        tabRepayViewModel.plansResult.observe(this@TabRepayGhanaActivity, Observer {
            val rowsResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (rowsResult.error != null) {
                showMessage(rowsResult.error)
            }
            if (rowsResult.success != null) {
                adapter.dataList = rowsResult.success
                adapter.notifyDataSetChanged()
            }
        })


        // 流程接口监听
        tabRepayViewModel.mainProcessResult.observe(this@TabRepayGhanaActivity, Observer {
            val mainProcessResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (mainProcessResult.error != null) {
                showMessage(mainProcessResult.error)
            }

            if (mainProcessResult.success != null) {
                tabRepayViewModel.nextRouter(mainProcessResult.success)
            }
        })

        // 页面需要跳转监听
        tabRepayViewModel.nextRouterResult.observe(this@TabRepayGhanaActivity, Observer {
            val nextRouterResult = it ?: return@Observer

            loading.visibility = View.GONE
            val intent = Intent(this@TabRepayGhanaActivity, nextRouterResult.nextPage)
            intent.putExtra("amount", sliderAmount.text.toString())
            startActivity(intent)
        })

        // 滑动监听
        slider.setProcessChangedListener(object : ITabRepayGhanaSliderListener {
            override fun onProcess(process: Float, curValue: Int) {
                // TODO: 更新金额值
                sliderAmount.text = curValue.toString()
            }
        })

        // 点击申请
        back.setOnClickListener {
            finish()
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineGhanaDialog().showNow(supportFragmentManager, "hotline")
            hitPoint("SHOW_HOTLINE")
        }

        // 点击申请
        submit.setOnClickListener {
            hitPoint("TAB_REPAY_APPLY_CLICK")

            val permissions = mutableListOf(
                android.Manifest.permission.READ_SMS,
                android.Manifest.permission.READ_PHONE_STATE
            )
            if (!checkPermissionsGranted(permissions)) {
                val intent = Intent(this@TabRepayGhanaActivity, PermissionGhanaActivity::class.java)
                startActivity(intent)
                return@setOnClickListener
            }
            try {
                AnalyticsUtil.saveDeviceS2SInfo()
            } catch (e: Exception) {
                e.printStackTrace()
            }

            // 判断可借金额
            val curAmount = sliderAmount.text.toString().trim()
            if (curAmount.isBlank() or (curAmount == "0")) {
                showMessage("The borrowable amount is insufficient.")
                return@setOnClickListener
            }

            tabRepayViewModel.mainProcess()
        }

        // 点击 loan
        tabMe.setOnClickListener {
            val intent = Intent(this@TabRepayGhanaActivity, MeGhanaActivity::class.java)
            startActivity(intent)
        }

        // 查询页面详情
        tabRepayViewModel.pageDetail()
    }

    override fun onResume() {
        super.onResume()
        hitPoint(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPoint(type = this::class.java.simpleName, isPageEnd = true)
    }

    /**
     * 检查权限是否同意
     */
    private fun checkPermissionsGranted(permissionList: List<String>): Boolean {
        val isNotAllGranted = permissionList.any {
            PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                ProjectApplication.instance,
                it
            )
        }
        return !isNotAllGranted
    }
}

interface ITabRepayGhanaPlanAdapter {
    fun onClickPlan(orderId: String)
}

class TabRepayGhanaPageAdapter(
    var dataList: List<JSONObject>,
    var onClickPlan: ITabRepayGhanaPlanAdapter? = null
) :
    RecyclerView.Adapter<TabRepayGhanaPageAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_ghana_tab_repay_activity_adapter, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val list: RecyclerView = view.findViewById(R.id.list)
        private val submit: TextView = view.findViewById(R.id.submit)

        fun bindData(item: JSONObject) {
            // 初始化adapter
            val planArray = item.getJSONArray("list")
            val planList = mutableListOf<JSONObject>()
            for (index in 0 until planArray.length()) {
                planList.add(planArray.optJSONObject(index) ?: JSONObject())
            }
            val adapter = TabRepayGhanaPlanAdapter(planList)
            list.layoutManager = LinearLayoutManager(list.context)
            list.adapter = adapter

            // 点击还款
            submit.setOnClickListener {
                onClickPlan?.apply {
                    onClickPlan(item.optString("orderId"))
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data: JSONObject = dataList[position]
        holder.bindData(data)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}

class TabRepayGhanaPlanAdapter(
    var dataList: List<JSONObject>
) :
    RecyclerView.Adapter<TabRepayGhanaPlanAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_ghana_tab_repay_plan_adapter, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val title: TextView = view.findViewById(R.id.title)
        private val detail: TextView = view.findViewById(R.id.detail)
        private val mark: TextView = view.findViewById(R.id.mark)

        fun bindData(item: JSONObject) {
            title.text = item.optString("showName")
            detail.text = item.optString("showDetail")

            // 标签
            val tag = item.optString("tag")
            mark.text = tag
            if (tag.isNotBlank()) {
                mark.visibility = View.VISIBLE
            } else {
                mark.visibility = View.GONE
            }

            // 加粗
            val isBold = item.optString("title")
            if (isBold.contains("YES", true)) {
                title.setTextColor(Color.parseColor("#222222"))
                title.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                detail.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
            } else {
                title.setTextColor(Color.parseColor("#999999"))
                title.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
                detail.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data: JSONObject = dataList[position]
        holder.bindData(data)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}

fun Context.showMessage(message: String) {
    Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
}
